package com.setup.trac.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.setup.trac.dao.DAOService;
import com.setup.trac.pojo.Utenti;
import com.setup.trac.service.MailSenderService;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.SQLCondition;
import com.setup.trac.util.TracSetupUtil;

public class AzzeraPasswordController extends AbstractController {

	
	private SearchService searchService;
	private TracSetupUtil tracSetupUtil;
	private DAOService daoService;
	private MailSenderService mailSenderService;
	private String view;
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		Utenti utente = getSearchService().findUtenteById(id);
		String newPassword = RandomStringUtils.randomAlphanumeric(8);
		String md5 = tracSetupUtil.md5(utente.getUsername()+newPassword);
		utente.setPrimoAccesso(true);
		utente.setPassword(md5);
		getDaoService().update(utente);
		utente.setPassword(newPassword);
		

		
		getMailSenderService().sendMessage(utente,"http://www.setup.torino.it/tracsetup/login.do");

		Map model = new HashMap();
		if(request.getParameter("cerca")!=null){
			setView("forward:cercaUtente.do");
		}
		ModelAndView mav = new ModelAndView(getView());
		mav.getModel().put("passwordAzzerata", "La nuova password è stata inviata all'indirizzo "+utente.getEmail());
		return mav;
	}

	public SearchService getSearchService() {
		return searchService;
	}
	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public TracSetupUtil getTracSetupUtil() {
		return tracSetupUtil;
	}

	public void setTracSetupUtil(TracSetupUtil tracSetupUtil) {
		this.tracSetupUtil = tracSetupUtil;
	}

	public DAOService getDaoService() {
		return daoService;
	}

	public void setDaoService(DAOService daoService) {
		this.daoService = daoService;
	}

	public MailSenderService getMailSenderService() {
		return mailSenderService;
	}

	public void setMailSenderService(MailSenderService mailSenderService) {
		this.mailSenderService = mailSenderService;
	}

	public String getView() {
		return view;
	}

	public void setView(String view) {
		this.view = view;
	}

}
